//
//  ORHomeViewController.m
//  NewsHots
//
//  Created by rimi on 2016/12/1.
//  Copyright © 2016年 zhongshuilian. All rights reserved.
//

#import "ORHomeViewController.h"
#import "ORSectionCollectionView.h"
#import "ORCollectionViewCell.h"
#import "ORRecommendViewController.h"
#import "ORCustomTableViewCell.h"

@interface ORHomeViewController () <UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray <UIImage *> *imageArray;
@property (nonatomic, strong) NSMutableArray <UIImageView *> *imageViewArray;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger currentPage; // 当前页
@property (nonatomic, strong) UIPageControl *pageControl; // 分页

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) NSArray *dataArray; //新闻频道

@property (nonatomic, strong) UICollectionView *collectionViews; // 集合视图

@property (nonatomic, strong) NSArray *recommendedArray; // 热点推荐

@property (nonatomic, assign) CGFloat height;


@end

@implementation ORHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    self.view.backgroundColor = [UIColor whiteColor];
    // 防止放在tableView的头部视图的滚动视图随着tableView的滑动而随着滑动
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initializeAppearence];
    
    [self scrollViewWirh];
//    [self initializeDataSource];
    [self.view addSubview:self.tableView];
    

    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(ScrollTimer:) userInfo:nil repeats:YES];
    
//    [self initNewsWith];
    [self initializeHeadNews];

}
#pragma mark - Custom initialize

-(void)initializeAppearence{
    // 网络请求
    NSString *appid = @"24762";
    NSString *sign = @"c0b7f94ce08f439d8d43e22b10fad680";
    NSDictionary *dic = @{@"showapi_appid":appid,@"showapi_sign":sign};
    [ORNetWorkRequestManager getMethod:@"http://route.showapi.com/109-34" withParames:dic Success:^(id respondObject) {
        NSLog(@"%@",respondObject[@"showapi_res_body"][@"channelList"]);
        self.dataArray = respondObject[@"showapi_res_body"][@"channelList"];
        
    } Failure:^(NSError *error) {
        
    }];

}

-(void)initNewsWith{
    NSString *appid = @"24762";
    NSString *sign = @"c0b7f94ce08f439d8d43e22b10fad680";
    NSDictionary *dic = @{@"showapi_appid":appid,@"showapi_sign":sign};
    [ORNetWorkRequestManager getMethod:@"http://route.showapi.com/109-34" withParames:dic Success:^(id respondObject) {
        NSLog(@"%@",respondObject);
        self.dataArray = respondObject[@"showapi_res_body"][@"channelList"];
        
    } Failure:^(NSError *error) {
        
    }];
}


-(void)initializeDataSource{
    //
    // 网络请求
    NSString *appid = @"24762";
    NSString *sign = @"c0b7f94ce08f439d8d43e22b10fad680";
    NSDictionary *dic = @{@"showapi_appid":appid,@"showapi_sign":sign,@"name":@"娱乐最新"};
    [ORNetWorkRequestManager getMethod:@"http://route.showapi.com/109-35" withParames:dic Success:^(id respondObject) {
        NSLog(@"%@",respondObject);
        
        
    } Failure:^(NSError *error) {
        
    }];
}

-(void)initializeHeadNews{
    // 推荐的网络请求
    NSDictionary *dic = @{@"key":@"6aa0243488ef2da834a378beabca0b25"};
    [ORNetWorkRequestManager getMethod:@"http://v.juhe.cn/toutiao/index" withParames:dic Success:^(id respondObject) {
        NSLog(@"%@",respondObject);
        _recommendedArray = respondObject[@"result"][@"data"];
        // 回到主线程更新（防止出现卡顿现象）
        [self.collectionViews reloadData];
      
    } Failure:^(NSError *error) {
        
    }];
}

-(void)scrollViewWirh{
    
    self.imageArray = [NSMutableArray array];
    
    for (int i = 0;  i < 6; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i+1]];
        [self.imageArray addObject:image];
    }
    self.imageViewArray = [NSMutableArray array];
    
    for (int i = 0; i < 3; i++) {
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:AAdaptionRect(i * kBaseWidth, 0, kBaseWidth/AAdaptationWidth(), 200)];
        
        imageView.image = self.imageArray[i];
        [self.imageViewArray addObject:imageView];
        [self.scrollView addSubview:self.imageViewArray[i]];
    }
    
    [self updataScrollView];
    [self.scrollView addSubview:self.pageControl];

}


// 定时器
- (void)ScrollTimer:(NSTimer *)sender {
    
    [self.scrollView setContentOffset:CGPointMake(2 * kBaseWidth, 0) animated:YES];
}

// 无线滑动：显示当前图片
-(void)updataScrollView{
    self.imageViewArray[1].image = self.imageArray[self.currentPage];
    
    if (self.currentPage == 0) {
        self.imageViewArray[0].image = self.imageArray.lastObject;
    } else {
        self.imageViewArray[0].image = self.imageArray[self.currentPage - 1];
    }
    
    if (self.currentPage == self.imageArray.count - 1) {
        self.imageViewArray[2].image = self.imageArray.firstObject;
    } else {
        self.imageViewArray[2].image = self.imageArray[self.currentPage + 1];
    }
    
    self.scrollView.contentOffset = CGPointMake(kBaseWidth, 0);}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    // 有两个scrollview 的时候，判断如果是tableview进行的话，就什么都不做；
    if (scrollView == self.tableView) {
        return;
    }
    self.timer.fireDate = [NSDate distantFuture];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    // 有两个scrollview 的时候，判断如果是tableview进行的话，就什么都不做；
    if (scrollView == self.tableView) {
        return;
    }
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 有两个scrollview 的时候，判断如果是tableview进行的话，就什么都不做；
    if (scrollView == self.tableView) {
        return;
    }
    
    [self reuses];
    [self updataScrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    [self reuses];
    [self updataScrollView];
}

- (void)reuses {
    
    if (self.scrollView.contentOffset.x == 0) {
        self.currentPage -= 1;
        if (self.currentPage < 0) {
            self.currentPage = self.imageArray.count - 1;
        }
        //*< 分页控制器 */
        if (self.pageControl.currentPage == 0) {
            self.pageControl.currentPage = self.imageArray.count - 1;
        } else {
            self.pageControl.currentPage = --self.pageControl.currentPage;
        }
        
    } else if (self.scrollView.contentOffset.x == 2 * kBaseWidth) {
        self.currentPage += 1;
        if (self.currentPage == self.imageArray.count) {
            self.currentPage = 0;
        }
        //*< 分页控制器 */
        if (self.pageControl.currentPage == self.imageArray.count - 1) {
            self.pageControl.currentPage = 0;
        } else {
            self.pageControl.currentPage = ++self.pageControl.currentPage;
        }
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 5;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 140;
    }else{
        return [ORCustomTableViewCell getHeight] +10;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *rese = @"UITableViewCell";
    ORCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rese];
    if (!cell) {
        cell = [[ORCustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rese];
    }
    if (indexPath.section == 0) {
        [cell.contentView addSubview:self.collectionViews];
    }else if (indexPath.section == 1){
        cell.titleLabel.text = @"ghost soul smile";
    }
    
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    return cell;
}

-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth/AAdaptationWidth(), kBaseHeight/AAdaptationWidth() - 70) style:UITableViewStyleGrouped];
        _tableView.tableHeaderView = self.scrollView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

-(UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth/AAdaptationWidth(), 200)];
        _scrollView.contentSize = CGSizeMake(kBaseWidth/AAdaptationWidth()*3, 0);
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

-(UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc]initWithFrame:AAdaptionRect((kBaseWidth - 200)/2, CGRectGetMaxY(self.scrollView.frame) -30, 200/AAdaptationWidth(), 20)];
        NSLog(@"%f",_pageControl.frame.origin.y);
        _pageControl.numberOfPages = self.imageArray.count;
        _pageControl.currentPageIndicatorTintColor = MainColor;
        _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    }
    return _pageControl;
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:AAdaptionRect(10, 10, 200, 20)];
        _titleLabel.text = @"    热点推荐";
//        _titleLabel.font = AAFont(15);
    }
    return _titleLabel;
}

#pragma mark - UICollectionViewDataSource

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ORCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"class" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.nameLabel.text = _recommendedArray[indexPath.row][@"title"];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_recommendedArray[indexPath.row][@"thumbnail_pic_s02"]]];
    }
    return cell;
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 20;
    }
}

#pragma mark - CollectionViewDelegate 点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
        ORRecommendViewController *recommened = [[ORRecommendViewController alloc]init];
        recommened.url = _recommendedArray[indexPath.row][@"url"];
        [self presentViewController:recommened animated:NO completion:nil];
}

-(UICollectionView *)collectionViews{
    if (!_collectionViews) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(80, 80);
        
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10.f;
        layout.minimumInteritemSpacing = (kBaseWidth - 80 * 4)/3;
        _collectionViews = [[UICollectionView alloc]initWithFrame:AAdaptionRect(10, 0, kBaseWidth-20, 120) collectionViewLayout:layout];
        _collectionViews.dataSource = self;
        _collectionViews.delegate = self;
        [_collectionViews registerClass:[ORCollectionViewCell class] forCellWithReuseIdentifier:@"class"];
        _collectionViews.backgroundColor = [UIColor whiteColor];
        _collectionViews.showsHorizontalScrollIndicator = NO;
    }
    return  _collectionViews;
}

@end
